package com.summer.peony.sso.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.summer.peony.common.entity.AjaxResult;
import com.summer.peony.common.utils.CookieUtils;
import com.summer.peony.sso.service.LoginService;

@RestController
@RequestMapping("/api")
@PropertySource("classpath:application.yml")
public class LoginController {

	@Value("${TOKEN.TOKEN_KEY}")
	private String TOKEN_KEY;

	@Autowired
	private LoginService loginService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public AjaxResult login(String username, String password, HttpServletRequest request,
			HttpServletResponse response) {
		AjaxResult ajaxResult = loginService.userLogin(username, password);
		// 判断是否登录成功
		if (ajaxResult.get("code").equals(0)) {
			String token = ajaxResult.get("data").toString();
			// 如果登录成功需要把token写入cookie
			CookieUtils.setCookie(request, response, TOKEN_KEY, token);
		}
		// 返回结果
		return ajaxResult;
	}
}
